﻿using log4net;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;
using Autofac;

namespace AppFx.BizTalk.Diagnostics.Telemetry
{
    public sealed class TelemetryManager
    {
        private static readonly ILog Log = LogFactory.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static TelemetryClient _client;
        private static object _myLock = new object();        

        public static TelemetryClient GetDefaultClient()
        {
            if (_client != null)
                return _client;

            lock(_myLock)
            {
                if (_client != null)
                    return _client;

                _client = new TelemetryClient();
            }
            return _client;
        }

        public static TelemetryClient GetNamedClient(string name, bool returnNullIfNotFound = false)
        {
            var telemetryConfig = TelemetryConfig.Current.Clients[name];
            if(telemetryConfig == null)
            {
                if (returnNullIfNotFound)
                    return null;

                Log.WarnFormat("There is no telemetry client config for: {0}", name);
                throw new ApplicationException(string.Format("The telemetry client configuration does not exist for client {0}", name));
            }
            
            if (telemetryConfig.DisableTelemetry)
            {
                var config = new TelemetryConfiguration();
                config.DisableTelemetry = telemetryConfig.DisableTelemetry;
                config.InstrumentationKey = telemetryConfig.TelemetryKey;

                var client = new TelemetryClient();
                client.Context.InstrumentationKey = telemetryConfig.TelemetryKey;
                return client;
            }
            else
            {
                var client = new TelemetryClient();
                client.Context.InstrumentationKey = telemetryConfig.TelemetryKey;
                return client;
            }
        }
    }
}
